package com.cg.managesystem.service;

import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Create tao on 2019/8/14
 */
public class RedisHashService<K, V> {
    private String rediskey = "RedisHashService";
    private BoundHashOperations<String, K, V> hashOps;

    public RedisHashService(RedisTemplate redisTemplate, String name) {
        if (name != null && !"".equals(name.trim())) {
            this.rediskey = name;
        }

        this.hashOps = redisTemplate.boundHashOps(this.rediskey);
    }

    public V get(K key) {
        return this.hashOps.get(key);
    }

    public V put(K key, V value) {
        V old = this.hashOps.get(key);
        this.hashOps.put(key, value);
        return old;
    }

    public V remove(K key) {
        V old = this.hashOps.get(key);
        this.hashOps.delete(new Object[]{key});
        return old;
    }

    public void clear() {
        this.hashOps.expire(0L, TimeUnit.MICROSECONDS);
    }

    public int size() {
        return this.hashOps.size().intValue();
    }

    public Set<K> keys() {
        return this.hashOps.keys();
    }

    public Collection<V> values() {
        return this.hashOps.values();
    }
}
